﻿

using ICSharpCode.SharpZipLib.GZip;
using Masuit.Tools;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace UtilsBase
{
    public class UtilsHttpHelper
    {

        public string sendPostRequest(string url, string data)
        {
            var response = "";

            try
            {
                using (var client = new HttpClient())
                {
                    client.Timeout = new TimeSpan(0, 0, 0, 30, 0);
                    client.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
                    client.DefaultRequestHeaders.Add("Keep-Alive", "timeout=6000");
                    client.DefaultRequestHeaders.Add("ContentType", "application/x-www-form-urlencoded");
                    client.DefaultRequestHeaders.Add("Accept", "*/*");
                    HttpContent content = new StringContent(data);
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                    var Result = client.PostAsync(url, content).Result;
                    content.Dispose();
                    if (Result.StatusCode == HttpStatusCode.OK)
                    {
                        response = Result.Content.ReadAsStringAsync().Result;
                    }
                    else
                    {
                        throw new Exception("Request Url is " + url + " Response is " + Result.StatusCode);
                    }
                    if (string.IsNullOrEmpty(response))
                    {
                        throw new Exception("Request Url is " + url + " Response is " + Result.StatusCode);
                    }

                }
            }
            catch (Exception ex)
            {
                //new UtilsFileHelper().log_WriteMessageAppend("error", " sendPostRequest请求 " + url + "parm: " + "data" + ex.ToString());
                throw;
            }

           // Console.WriteLine(response);
            return response;
        }


        public static bool checkUrlIsOK(string url)
        {
            try
            {
                var client = new HttpClient();
                var result = client.GetAsync(url).Result;
                if (result.StatusCode.ToString() != "OK")
                {
                    // new UtilsFileHelper().upgradeServer_WriteMessageAppend(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").ToString() + "下载连接出错 url :" + url);
                    Console.WriteLine("连接异常：" + url);
                    return false;
                }
                Console.WriteLine("连接正常：" + url);
                return true;
            }
            catch (Exception ex)
            {
                // new UtilsFileHelper().log_WriteMessageAppend("error", "" + "下载连接出错:" + url);
                //  new UtilsFileHelper().log_WriteMessageAppend("error", "" + ex.ToString());

                Console.WriteLine("连接异常：" + ex);
                return false;
            }
        }
        public string sendGetMethod(string url)
        {

            var client = new HttpClient();
            return client.GetAsync(url).Result.Content.ReadAsStringAsync().Result;

        }


        public string sendPostRequestV2(string url, string data)
        {

            var response = "";

            // try
            //  {
            using (var client = new HttpClient())
            {

                client.Timeout = TimeSpan.FromSeconds(5);
                StringContent strcontent = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
                var Result = client.PostAsync(url, strcontent).Result;
                if (Result.StatusCode == HttpStatusCode.OK)
                {
                    response = Result.Content.ReadAsStringAsync().Result;
                }
                else
                {
                    throw new Exception("Request Url is " + url + " Response is " + Result.StatusCode);
                }
                if (string.IsNullOrEmpty(response))
                {
                    throw new Exception("Request Url is " + url + " Response is " + Result.StatusCode);
                }

            }
            //}
            //catch (Exception ex)
            //{
            //    throw;
            //}

            //Console.WriteLine(response);
            return response;
        }
        static HttpClient client = null;
        //public string sendPostToGateWayCloodBridgeAPI(string url, object data)
        //{
        //    string content = JsonConvert.SerializeObject(data);
        //    string timeStamp = UtilsDateTime.getTimeStamp();
        //    string sign = UtilsDecrypt.DoMd5Encode(timeStamp + JsonConvert.SerializeObject(data) + "gatewayapi", "32");
        //    string urlParameter = "?timeStamp=" + timeStamp + "&sign=" + sign+ "&content="+ content;
        //    url = url + urlParameter;

        //    //Console.WriteLine(DateTime.Now.ToString());
        //    //Console.WriteLine(url);
        //    var response = "";

        //    try
        //    {
        //        if (client == null)
        //        {
        //            client = new HttpClient();
        //            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        //        }
        //        StringContent strcontent = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
        //      //  var Result = client.PostAsync(url, strcontent).Result;
        //        var Result = client.PostAsync(url,null).Result;
        //        if (Result.StatusCode == HttpStatusCode.OK)
        //        {
        //            response = Result.Content.ReadAsStringAsync().Result;
        //            return response;
        //        }
        //        else
        //        {
        //            throw new Exception("Request Url is " + url + " Response is " + Result.StatusCode);
        //        }
        //        //if (string.IsNullOrEmpty(response))
        //        //{
        //        //    throw new Exception("Request Url is " + url + " Response is " + Result.StatusCode);
        //        //}
        //    }
        //    catch (Exception ex)
        //    {
        //        throw;
        //    }
        //}


        public string httpClientPost(string url, string data)
        {
            try
            {
                StringContent strcontent = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");


                var client = new HttpClient();
                var result = client.PostAsync(url, strcontent).Result;
                if (result.StatusCode.ToString() != "OK")
                {
                    Console.WriteLine("连接异常：" + url);
                    return "";
                }
                return result.Content.ReadAsStringAsync().Result;
            }
            catch (Exception ex)
            {
                Console.WriteLine("连接异常：" + ex);
                return "";
            }
        }


        //public string getAuthorization(string url, string AccessToken)
        //{
        //    var client = new RestClient(url);
        //    var request = new RestRequest();//get提交
        //    string token = "Bearer " + AccessToken;
        //    client.AddDefaultHeader("Authorization", token);//附加token验证信息   登陆时获取
        //    var response = client.Get(request);

        //    if (response.StatusCode == HttpStatusCode.OK)
        //    {
        //        try
        //        {
        //            return response.Content;
        //        }
        //        catch (Exception ex)
        //        {
        //            throw;
        //        }
        //    }
        //    else
        //    {
        //        return "网络错误。{response.StatusCode.ToString()}";
        //    }

        //}


        /// <summary>
        /// 使用post方法异步请求
        /// </summary>
        /// <param name="url">目标链接</param>
        /// <param name="json">发送的参数字符串，只能用json</param>
        /// <returns>返回的字符串</returns>
        public static async Task<string> postAsyncJson(string url, string json)
        {
            HttpClient client = new HttpClient();
            HttpContent content = new StringContent(json);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            HttpResponseMessage response = await client.PostAsync(url, content);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            return responseBody;
        }

        /// <summary>
        /// 使用post方法异步请求
        /// </summary>
        /// <param name="url">目标链接</param>
        /// <param name="data">发送的参数字符串</param>
        /// <returns>返回的字符串</returns>
        public async Task<string> postAsync(string url, string data, Dictionary<string, string> header = null, bool Gzip = false)
        {
            HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false });

            if (header != null)
            {
                client.DefaultRequestHeaders.Clear();
                foreach (var item in header)
                {
                    client.DefaultRequestHeaders.Add(item.Key, item.Value);
                }
            }
            if (string.IsNullOrEmpty(data))
            {
                data = "";
            }
            client.Timeout = TimeSpan.FromSeconds(20);
            HttpContent content = new StringContent(data, Encoding.UTF8, "application/x-www-form-urlencoded");
            HttpResponseMessage response = await client.PostAsync(url, content);
            response.EnsureSuccessStatusCode();
            string responseBody = "";
            if (Gzip)
            {
                GZipInputStream inputStream = new GZipInputStream(await response.Content.ReadAsStreamAsync());
                responseBody = new StreamReader(inputStream).ReadToEnd();
                inputStream.Dispose();
            }
            else
            {
                responseBody = await response.Content.ReadAsStringAsync();

            }
            response.Dispose();
            content.Dispose();
            client.Dispose();
            return responseBody;
        }


        /// <summary>
        /// 使用post方法异步请求
        /// </summary>
        /// <param name="url">目标链接</param>
        /// <param name="data">发送的参数字符串</param>
        /// <returns>返回的字符串</returns>
        public async Task<string> postJsonAsync(string url, string data, Dictionary<string, string> header = null, bool Gzip = false)
        {
            HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false }); //带上UseCookies 到新页面，比如登录信息保存

            if (header != null)
            {
                client.DefaultRequestHeaders.Clear();
                foreach (var item in header)
                {
                    client.DefaultRequestHeaders.Add(item.Key, item.Value);
                }
            }
            if (string.IsNullOrEmpty(data))
            {
                data = "";
            }
            client.Timeout = TimeSpan.FromSeconds(10);
            HttpContent content = new StringContent(data, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync(url, content);
            response.EnsureSuccessStatusCode();
            string responseBody = "";
            if (Gzip)
            {
                GZipInputStream inputStream = new GZipInputStream(await response.Content.ReadAsStreamAsync());
                responseBody = new StreamReader(inputStream).ReadToEnd();
                inputStream.Dispose();
            }
            else
            {
                responseBody = await response.Content.ReadAsStringAsync();

            }
            response.Dispose();
            content.Dispose();
            client.Dispose();
            return responseBody;
        }



        /// <summary>
        /// 使用get方法异步请求
        /// </summary>
        /// <param name="url">目标链接</param>
        /// <returns>返回的字符串</returns>
        public async Task<string> getAsync(string url, Dictionary<string, string> header = null, bool Gzip = false)
        {

            HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false });
            if (header != null)
            {
                client.DefaultRequestHeaders.Clear();
                foreach (var item in header)
                {
                    client.DefaultRequestHeaders.Add(item.Key, item.Value);
                }
            }
            HttpResponseMessage response = await client.GetAsync(url);
            response.EnsureSuccessStatusCode();//用来抛异常的
            string responseBody = "";
            if (Gzip)
            {
                GZipInputStream inputStream = new GZipInputStream(await response.Content.ReadAsStreamAsync());
                responseBody = new StreamReader(inputStream).ReadToEnd();
                inputStream.Dispose();
            }
            else
            {
                responseBody = await response.Content.ReadAsStringAsync();

            }
            response.Dispose();
            client.Dispose();
            return responseBody;
        }

        /// <summary>
        /// 使用post返回异步请求直接返回对象
        /// </summary>
        /// <typeparam name="T">返回对象类型</typeparam>
        /// <typeparam name="T2">请求对象类型</typeparam>
        /// <param name="url">请求链接</param>
        /// <param name="obj">请求对象数据</param>
        /// <returns>请求返回的目标对象</returns>
        public static async Task<T> postObjectAsync<T, T2>(string url, T2 obj)
        {
            string json = JsonConvert.SerializeObject(obj);
            string responseBody = await postAsyncJson(url, json); //请求当前账户的信息
            return JsonConvert.DeserializeObject<T>(responseBody);//把收到的字符串序列化
        }

        /// <summary>
        /// 使用Get返回异步请求直接返回对象
        /// </summary>
        /// <typeparam name="T">请求对象类型</typeparam>
        /// <param name="url">请求链接</param>
        /// <returns>返回请求的对象</returns>
        public static async Task<T> getObjectAsync<T>(string url)
        {
            string responseBody = await new UtilsHttpHelper().getAsync(url); //请求当前账户的信息
            return JsonConvert.DeserializeObject<T>(responseBody);//把收到的字符串序列化
        }
        /// <summary>
        /// http请求接口,经测试，跟httpclient速度一样的
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="data">数据，json格式化后的数据</param>
        /// <param name="method">方法 POST，或者get</param>
        /// <returns></returns>
        public string RestHttpRequest(string url, string data,string authorization_bearer_access_token, Method method , string file = null)
        {
            try
            {
                var client = new RestClient( url);
                var request = new RestRequest();
                request.Method=method;
                // request.RequestFormat = DataFormat.Json;

               

                if (file == null)
                   // request.AddHeader("Content-Type", "application/json");
                request.AddHeader("Content-Type", "application/json; charset=UTF-8");
                else
                {

                    request.AddHeader("Content-Type", "multipart/form-data");
                    //request.AddHeader("user_id", UserCache.Current_UserId.ToString());
                    //request.AddHeader("username", System.Web.HttpUtility.UrlEncode(UserCache.Current_UserName));
                }
                request.Timeout = 10000;
                if (!string.IsNullOrEmpty(data))
                    request.AddParameter("application/json; charset=utf-8", data, ParameterType.RequestBody);
                if (!string.IsNullOrEmpty(authorization_bearer_access_token))
                    request.AddHeader("authorization", "Bearer " + authorization_bearer_access_token);
                if (file != null)
                    request.AddFile("file", file);
                RestResponse response = client.Execute(request);
                var responseContent = response.Content;
                return responseContent;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}
